import RFB from '/static/vnc/core/rfb.js';

function readQueryVariable(name, defaultValue) {
    const re = new RegExp('.*[?&]' + name + '=([^&#]*)'),
        match = document.location.href.match(re);
    if (match) {
        return decodeURIComponent(match[1]);
    }
    return defaultValue;
}


/**
 *
 * @returns {{connect: connect}}
 */
export function vnc(connect_before=()=>{}, connect_after=()=>{}, disconnected=()=>{}) {
    let rfb;
    return {
        connect: function (token) {
            connect_before();
            let desktopName;
            const host = readQueryVariable('host', window.location.hostname);
            let port = readQueryVariable('port', window.location.port);
            const password = readQueryVariable('password');
            const path = readQueryVariable('path', 'websockify');
            let url;
            if (window.location.protocol === "https:") {
                url = 'wss';
            } else {
                url = 'ws';
            }
            url += '://' + host;
            if (port) {
                url += ':' + port;
            }
            url += '/' + path + "?token=" + token;
            if(this.rfb != null){
                this.disconnect();
            }
            rfb = new RFB(document.getElementById('screen'), url, {credentials: {password: password}});
            rfb.addEventListener("connect", function (e) {
                connect_after();
                console.log("Connected to " + desktopName);
            });

            rfb.addEventListener("disconnect", (e) => {
                disconnected();
                if (e.detail.clean) {
                    console.log("Disconnected");
                } else {
                    console.log("Something went wrong, connection is closed");
                }
            },);

            rfb.addEventListener("credentialsrequired", (e) => {
                const password = prompt("Password Required:");
                rfb.sendCredentials({password: password});
            });

            rfb.addEventListener("desktopname", function (e) {
                desktopName = e.detail.name;
            });

            rfb.viewOnly = readQueryVariable('view_only', false);

            rfb.scaleViewport = readQueryVariable('scale', false);
            if(rfb != null){
                this.rfb = rfb
            }
        },
        disconnect: function(){
            if(this.rfb != null) {
                this.rfb.disconnect();
                this.rfb = null;
            }
        }
    }
}